<template>
  <el-dialog @close="reset" fullscreen :title="goodsData.id>0?'编辑':'新增'" :visible.sync="info.isShow">
    <el-form
      ref="goodsForm"
      label-width="80px"
      :model="goodsData"
      :rules="rules"
    >
      <el-tabs v-model="activeName">
        <el-tab-pane label="基础信息" name="first">
          <el-form-item label="一级分类" prop="first_cateid">
            <el-select
              v-model="goodsData.first_cateid"
              @change="firstCateChange"
            >
              <el-option
                v-for="item in cateList"
                :key="item.id"
                :value="item.id"
                :label="item.catename"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="二级分类" prop="second_cateid">
            <el-select v-model="goodsData.second_cateid">
              <el-option
                v-for="item in secondCateList"
                :key="item.id"
                :value="item.id"
                :label="item.catename"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="商品名称" prop="goodsname">
            <el-input
              placeholder="商品名称"
              v-model.trim="goodsData.goodsname"
            ></el-input>
          </el-form-item>
          <el-form-item label="商品价格" prop="price">
            <el-input
              placeholder="商品价格"
              v-model="goodsData.price"
            ></el-input>
          </el-form-item>
          <el-form-item label="市场价格" prop="market_price">
            <el-input
              placeholder="市场价格"
              v-model="goodsData.market_price"
            ></el-input>
          </el-form-item>
          <el-form-item label="商品图片" prop="img">
            <el-upload
              action="#"
              :auto-upload="false"
              list-type="picture-card"
              :limit="1"
              :on-exceed="limitTips"
              :on-change="imgChange"
              ref="upload"
              :file-list="imgList"
            >
              <i class="el-icon-plus"></i>
            </el-upload>
          </el-form-item>
          <el-form-item label="商品规格" prop="specsid">
            <el-select v-model="goodsData.specsid" @change="specsChange">
              <el-option
                v-for="item in specsList"
                :key="item.id"
                :value="item.id"
                :label="item.specsname"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="规格属性" prop="specsattr">
            <!-- multiple: 实现多选 -->
            <el-select v-model="goodsData.specsattr" multiple>
              <el-option
                v-for="(item, index) in specsAttrs"
                :key="index"
                :value="item"
                :label="item"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="是否新品" prop="isnew">
            <el-switch
              v-model="goodsData.isnew"
              :active-value="1"
              :inactive-value="0"
            ></el-switch>
          </el-form-item>
          <el-form-item label="是否热卖" prop="ishot">
            <el-switch
              v-model="goodsData.ishot"
              :active-value="1"
              :inactive-value="0"
            ></el-switch>
          </el-form-item>
          <el-form-item label="商品状态" prop="status">
            <el-radio-group v-model="goodsData.status">
              <el-radio :label="1">正常</el-radio>
              <el-radio :label="2">禁用</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-tab-pane>
        <el-tab-pane label="商品详情" name="second">
          <el-form-item label-width="0" prop="description">
            <wangeditor
              id="description"
              v-model="goodsData.description"
              style="height: 380px"
              width="100%"
              ref="description"
            />
          </el-form-item>
        </el-tab-pane>
      </el-tabs>
    </el-form>
    <div class="dialog-footer" slot="footer">
      <el-button @click="reset">取消</el-button>
      <el-button type="primary" @click="submit">提交</el-button>
    </div>
  </el-dialog>
</template>

<script>
const initData = {
  first_cateid: "",
  second_cateid: "",
  goodsname: "",
  price: "",
  market_price: "",
  img: null,
  description: "",
  specsid: "",
  specsattr: [],
  isnew: "",
  ishot: "",
  status: "",
};
// 导入vuex辅助函数
import { mapState, mapActions } from "vuex";
// 导入富文本编辑器
import wangeditor from "vue-wangeditor";
export default {
  components: { wangeditor },
  props: ["info"],
  computed: {
    ...mapState("cate", ["cateList"]),
    ...mapState("specs", ["specsList"]),
  },
  methods: {
    ...mapActions("cate", ["getCateListAction"]),
    ...mapActions("specs", ["getSpecsListAction"]),
    // 更新表单数据
    setFormData(obj) {
      // 删除多余属性
      delete obj.firstcatename;
      delete obj.secondcatename;
      this.goodsData = { ...obj };
      // 手动调用一级分类下拉框change事件处理函数
      this.firstCateChange(obj.first_cateid, false);
      // 更新图片上传组件默认需要展示的图片列表
      if (obj.img !== "null") {
        this.imgList = [{ url: this.$baseUrl + obj.img }];
      }
      // 手动调用规格下拉框change事件处理函数
      this.specsChange(obj.specsid, false);
      this.goodsData.specsattr = this.goodsData.specsattr.split(",");
      // 手动设置富文本编辑器的内容
      setTimeout(() => {
        this.$refs.description.setHtml(obj.description);
      }, 200);
    },
    // 数据重置
    reset() {
      // 重置表单
      this.goodsData = {
        ...initData,
      };
      // 关闭对话框
      this.info.isShow = false;
      // 手动清除富文本编辑器的内容
      this.$refs.description.setHtml("");
      // 移除图片上传组件中已选择的图片
      this.$refs.upload.clearFiles();
    },
    submit() {
      this.$refs.goodsForm.validate((valid) => {
        if (valid) {
          // 手动获取富文本编辑器的内容
          this.goodsData.description = this.$refs.description.getHtml();
          // 将goodsData => FormData
          const fd = new FormData();
          for (let key in this.goodsData) {
            fd.append(key, this.goodsData[key]);
          }
          const url=this.goodsData.id>0?'/goodsedit':'/goodsadd';
          this.$axios.post(url, fd).then((res) => {
            if (res.code === 200) {
              this.$message.success(res.msg);
              // 更新商品数据: 通知父组件更新数据
              this.$emit("goodsUpdate");
              // 重置数据
              this.reset();
            } else {
              this.$message.error(res.msg);
            }
          });
        }
      });
    },
    imgChange(file) {
      // 手动同步图片信息
      this.goodsData.img = file.raw;
    },
    // 上传图片数量超过上限的提示
    limitTips() {
      this.$message.warning("此处只能上传一张图片");
    },
    // 规格下拉框change事件处理函数
    specsChange(specsId, flag = true) {
      // 根据规格id查询规格索引
      const index = this.specsList.findIndex((item) => item.id === specsId);
      // 更新规格属性
      this.specsAttrs = this.specsList[index].attrs;
      // 清空用户之前选择的规格属性(当通过鼠标点击规格下拉框的时候, 应该清除之前的规格属性; 当手动调用specsChange的时候, 不需要清除)
      if (flag) {
        this.goodsData.specsattr = [];
      }
    },
    // 一级分类下拉框change事件处理函数
    firstCateChange(firstCateId, flag = true) {
      // 根据一级分类id查找一级分类索引
      const index = this.cateList.findIndex((item) => item.id === firstCateId);
      // 清除用户之前选择的二级分类信息(当用户通过鼠标点击一级分类下拉框的时候, 需要清除已选择二级分类信息; 当手动调用firstCateChange的时候, 不需要清除已选择的二级分类信息)
      if (flag) {
        this.goodsData.second_cateid = "";
      }
      // 更新二级分类
      if (this.cateList[index].children) {
        this.secondCateList = this.cateList[index].children;
      } else {
        // 如果当前一级分类没有对应的二级分类, 清空之前的二级分类数据
        this.secondCateList = [];
      }
    },
  },
  created() {
    // 请求分类列表
    this.getCateListAction();
    // 请求商品规格列表
    this.getSpecsListAction({ page: 1, size: 100 });
  },
  data() {
    // 自定义表单校验函数
    const validDesc = (rule, value, callback) => {
      // 获取富文本编辑的内容
      const description = this.$refs.description.getHtml();
      if (description === "<p><br></p>") {
        return callback(new Error("请输入商品介绍"));
      }
      // 表示表单校验通过
      callback();
    };
    return {
      // 图片上传组件默认需要展示的图片列表
      imgList: [],
      // 二级分类
      secondCateList: [],
      // 规格属性
      specsAttrs: [],
      activeName: "first",
      // 表单数据对象
      goodsData: {
        ...initData,
      },
      // 表单校验规则对象
      rules: {
        first_cateid: { required: true, message: "请选择", trigger: "blur" },
        second_cateid: { required: true, message: "请选择", trigger: "blur" },
        goodsname: { required: true, message: "请输入", trigger: "blur" },
        price: { required: true, message: "请输入", trigger: "blur" },
        market_price: { required: true, message: "请输入", trigger: "blur" },
        specsid: { required: true, message: "请选择", trigger: "blur" },
        specsattr: { required: true, message: "请选择", trigger: "blur" },
        isnew: { required: true, message: "请选择", trigger: "blur" },
        ishot: { required: true, message: "请选择", trigger: "blur" },
        status: { required: true, message: "请选择", trigger: "blur" },
        description: { validator: validDesc, trigger: "blur" },
      },
    };
  },
};
</script>

<style>
.wangEditor-container {
  height: 380px !important;
}
</style>